import subprocess
import os

# venv_path = r".\project"

# 激活虚拟环境并获取 pip 列表
def get_pip_list(venv_path):
    # 构造激活虚拟环境和获取 pip 列表的命令
    activate_script = os.path.join(venv_path, 'Scripts', 'activate')
    pip_list_command = "pip list"

    # 使用 shell 执行命令
    command = f"{activate_script} && {pip_list_command}"

    try:
        # 使用 Popen 执行命令并捕获输出
        process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, encoding="cp936")
        stdout, stderr = process.communicate()

        # 检查命令是否成功执行
        if process.returncode == 0:
            return stdout.strip()
        else:
            return f"Error: {stderr.strip()}"
    except Exception as e:
        return f"Exception occurred: {str(e)}"


# 主函数
def main(current_project_path):
    # 获取 pip 列表
    venv_path = current_project_path
    pip_list = get_pip_list(venv_path)

    # 打印 pip 列表
    print(pip_list)
    lines = pip_list.split('\n')
    # 解析每一行并存储为字典
    packages = []
    i = 0
    for line in lines:
        if i > 1:
            if line.strip():  # 跳过空行
                parts = line.split()  # 默认按空格分割
                if len(parts) >= 2:
                    package = parts[0]
                    version = parts[1]
                    packages.append({"Package": package, "Version": version})
        else:
            i += 1
    print(packages)
    return packages


if __name__ == "__main__":
    main()